package com.neusoft.neuiotms.dcam.fixed.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.SpareTypeDTO;
import com.neusoft.neuiotms.dcam.fixed.model.SpareType;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetTypeRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.SpareTypeRepository;

@Component
public class SpareTypeConverter extends AbstractConverter<SpareType, SpareTypeDTO> {

    @Autowired
    private SpareTypeRepository spareTypeRepository;

    @Autowired
    private AssetTypeRepository assetTypeRepository;

    @Override
    public SpareType toModel(final SpareTypeDTO dto) {
        final SpareType model;
        if (dto.isNew()) {
            model = new SpareType();
        } else {
            model = this.spareTypeRepository.getOne(dto.getId());
        }
        model.setCode(dto.getCode());
        model.setName(dto.getName());
        model.setUnit(dto.getUnit());
        if (dto.getParentCode() != null) {
            model.setParent(this.assetTypeRepository.findByCode(dto.getParentCode()));
        }

        return model;
    }

    @Override
    public SpareTypeDTO toDTO(final SpareType model, final boolean forListView) {
        final SpareTypeDTO dto = new SpareTypeDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        dto.setUnit(model.getUnit());
        if (model.getParent() != null) {
            dto.setParentName(model.getParent().getName());
            dto.setParentCode(model.getParent().getCode());
        }

        return dto;
    }

}
